﻿using System;
using System.Web.Mvc;
using System.IO;
using System.Web;

namespace AdventureWorks.View.Infra
{
	public class ImageResult : ActionResult
	{
		private Stream ImageStream { get; set; }
		private String ContentType { get; set; }

		public ImageResult(Byte[] imageBytes)
		{
			if (imageBytes != null)
			{
				ImageStream = new MemoryStream(imageBytes);
				ContentType = "image/gif";
			}
			else
			{
				ImageStream = new MemoryStream();
				ContentType = "";
			}
		}

		public override void ExecuteResult(ControllerContext context)
		{
			if (context == null)
				throw new ArgumentNullException("context");

			HttpResponseBase response = context.HttpContext.Response;
			response.ContentType = ContentType;

			var buffer = new Byte[4096];
			while (true)
			{
				int read = ImageStream.Read(buffer, 0, buffer.Length);
				if (read == 0)
					break;

				response.OutputStream.Write(buffer, 0, read);
			}
			response.End();
		}
	}
}
